import constantRoutes from "@/router/constantRoutes"
import { login, register, getUserInfo, logout, getNoReadMsgList, getNoReadMsgCount, updateMsgState, getFriendList, updateFriendMsgState, refreshTokenApi } from "@/apis/user"

const state = {
    isLogin: false, // 登录状态
    userInfo: null, // 用户信息
    menuList: [], // 菜单列表
    defaultAvatar: require('@/assets/images/defaultAvatar.png'), // 默认头像
    isAttention: false, // 是否关注
    token: '',
    refreshToken: '', // 刷新令牌
    accessCreateTime: '', // 令牌创建时间
    noReadMsgList: [], // 未读消息列表
    originalNoReadMsgList: [], // 原始未读消息列表
    noReadMsgCount: 0, // 未读消息数量
    friendList: [], // 好友列表
    currentFriendId: null, // 当前聊天好友id
    currentFriend: null, // 当前聊天好友
    refreshTokenExpired: false, // 新增：标记refreshToken是否过期
}

const mutations = {
    // 存储 token 令牌
    setToken(state, { accessToken, refreshToken, accessCreateTime }) {
        state.token = accessToken
        state.refreshToken = refreshToken
        state.accessCreateTime = accessCreateTime
    },

    // 设置是否刷新令牌过期
    setRefreshTokenExpired(state, isExpired = true) {
        state.refreshTokenExpired = isExpired
    },

    // 存储用户信息
    setUserInfo(state, data) {
        state.userInfo = data
    },

    // 设置登录状态
    setLoginState(state, data) {
        state.isLogin = data
    },

    // 设置菜单
    setMenuList(state, data) {
        state.menuList = data
    },

    // 退出登录
    logout(state) {
        state.userInfo = null
        state.isLogin = false
        state.currentFriendId = null
        state.friendList = []
        state.currentFriendId = null
        state.token = ''
        state.refreshToken = ''
        state.accessCreateTime = ''
        state.refreshTokenExpired = false
    },

    // 存储未读消息列表
    setNoReadMsgList(state, data) {
        state.noReadMsgList = data
    },

    setOriginalNoReadMsgList(state, data) {
        state.originalNoReadMsgList = data
    },

    // 存储未读消息数量
    setNoReadMsgCount(state, data) {
        state.noReadMsgCount = data
    },
    
    // 存储好友列表
    setFriendList(state, data) {
        const map = new Map()
        data.forEach(item => {
            if (!map.has(item.userId)) {
            map.set(item.userId, item) // 就把这一条好友信息以 userId 为键、item 为值存进 Map
            }
        })
        state.friendList = Array.from(map.values()) // 把 Map 里所有值（即去重后的好友对象）转回数组
    },

    // 设置当前好友
    setCurrentFriend(state, data) {
        // 如果data为undefined，则直接返回，不进行任何操作
        if (!data) {
            // 可以选择清空当前选中的好友
            state.currentFriend = null;
            state.currentFriendId = null;
            // 同时将所有好友的active状态设置为false
            state.friendList.forEach(item => {
                item.active = false;
            });
            return;
        }

        state.currentFriend = data
        state.currentFriendId = data.userId ? data.userId : data.senderId

        state.friendList.forEach(item => {
            item.active = false
            if (item.userId === (data.userId ? data.userId : data.senderId)) {
                item.active = true
            }
        })
    },

    // 清空当前好友
    clearCurrentFriend(state) {
        state.currentFriend = null;
        state.currentFriendId = null;
        state.friendList.forEach(item => (item.active = false));
    },

    // 修改好友未读消息数量
    setNoReadCount(state, data) {
        state.friendList.forEach(item => {
            if (item.userId === data.userId) {
                item.lastMessageTime = data.lastMessageTime
                item.lastMessage = data.lastMessage

                // 如果是已读消息，则清空未读消息数量
                if (data.isReadState === 0 || data.isReadState === 1) {
                    item.noReadCount = 0
                    return
                }

                // 如果data里面没有isSender字段（即undefined），则加上isSender字段为true
                if (!data.hasOwnProperty('isSender')) {
                    data.isSender = true;
                }

                // 如果isSender为false(不是自己发送的消息)，让未读消息 + 1
                if (data.isSender === false) {
                    item.noReadCount++;
                }
            }
        })
    },
}

const actions = {
    // 登录
    login(ctx, data) {
        return new Promise((resolve, reject) => {
            login(data).then(res => {
                if (res.code === 200) {
                    ctx.commit('setToken', {
                        accessToken: res.data.accessToken,
                        refreshToken: res.data.refreshToken,
                        accessCreateTime: res.data.createTime
                    })
                    ctx.commit('setLoginState', true)
                    ctx.dispatch('getUserInfo')
                    ctx.dispatch('getNoReadMsgCount')
                    ctx.dispatch('getNoReadMsgList')
                    resolve(res)
                } else {
                    reject(res)
                }
            }).catch(err => {
                reject(err)
            })
        })
    },

    // 刷新令牌
    refreshToken(ctx, data) {
        return new Promise((resolve, reject) => {
            refreshTokenApi({ refreshToken: data.refreshToken }).then(res => {
                if (res.code === 200) {
                    ctx.commit('setToken', {
                        accessToken: res.data.accessToken,
                        refreshToken: res.data.refreshToken,
                        accessCreateTime: res.data.createTime
                    })
                    resolve(res.data)
                } else {
                    ctx.commit('setRefreshTokenExpired', true)
                    reject(res)
                }
            }).catch(err => {
                ctx.commit('setRefreshTokenExpired', true)
                reject(err)
            })
        })
    },

    // 注册
    register(ctx, data) {
        return new Promise((resolve, reject) => {
            register(data).then(res => {
                if (res.code === 200) {
                    resolve(res)
                } else {
                    reject(res)
                }
            }).catch(err => {
                reject(err)
            })
        })
    },

    // 登出
    logout(ctx, data) {
        return new Promise((resolve, reject) => {
            logout(data).then(res => {
                if (res.code === 200) {
                    ctx.commit('logout')
                    resolve(res)
                } else {
                    ctx.commit('logout')
                    resolve(res)
                }
            }).catch(err => {
                console.log(err)
                // 即使登出接口失败，也要清除本地状态
                ctx.commit('logout')
                resolve({ code: 200, message: '本地登出成功' })
            })
        })
    },

    // 获取用户信息
    getUserInfo(ctx, data) {
        getUserInfo().then(res => {
            if (res.code === 200) {
                ctx.commit('setUserInfo', res.data)
            }
        }).catch(err => {
            console.log(err)
        })
    },

    // 获取菜单列表
    getMenuList(ctx) {
        let routes = JSON.parse(JSON.stringify(constantRoutes))
        routes = routes.filter(item => item.name !== 'NotFound')
        let data = mapMenus(routes)
        ctx.commit('setMenuList', data)
    },

    // 获取未读消息列表
    getNoReadMsgList(ctx) {
        return new Promise((resolve, reject) => {
            getNoReadMsgList().then(res => {
                if (res.code === 200) {
                    ctx.commit('setOriginalNoReadMsgList', res.data)
                    // 使用reduce进行分组
                    const groupedMessages = res.data.reduce((acc, message) => {
                        const senderId = message.senderId;
                        const existing = acc.find(item => item.senderId === senderId);
                        
                        if (existing) {
                            existing.unreadCount++;
                            // 更新为最新消息
                            if (new Date(message.createTime) > new Date(existing.lastMessageTime)) {
                                existing.lastMessage = message.content;
                                existing.lastMessageTime = message.createTime;
                            }
                        } else {
                            acc.push({
                                chatId: message.chatId,
                                senderId: senderId,
                                senderUsername: message.senderUsername,
                                senderNickName: message.senderNickName,
                                senderAvatar: message.senderAvatar,
                                senderJob: message.senderJob,
                                senderState: message.senderState,
                                senderSex: message.senderSex,
                                lastMessage: message.content,
                                lastMessageTime: message.createTime,
                                type: message.type,
                                unreadCount: 1
                            });
                        }

                        return acc;
                    }, []);

                    // 按最后消息时间倒序排列并取前5条
                    const sortedMessages = groupedMessages.sort((a, b) =>
                        new Date(b.lastMessageTime) - new Date(a.lastMessageTime)
                    ).slice(0, 5);

                    ctx.commit('setNoReadMsgList', sortedMessages)
                    resolve(res)
                } else {
                    reject(res)
                }
            }).catch(err => {
                console.log(err)
                reject(err)})
        })
    },

    // 获取未读消息数量
    getNoReadMsgCount(ctx) {
        getNoReadMsgCount().then(res => {
            if (res.code === 200) {
                ctx.commit('setNoReadMsgCount', res.data)
            }
        }).catch(err => {
            console.log(err)
        })
    },

    // 修改用户消息状态
    updateMsgState(ctx, data) {
        return new Promise((resolve, reject) => {
            updateMsgState(data).then(res => {
                if (res.code === 200) {
                    resolve(res)
                } else {
                    reject(res)
                }
            }).catch(err => {
                reject(err)
                console.log(err)
            })
        })
    },

    // 查询好友列表
    getFriendList(ctx) {
        return new Promise((resolve, reject) => {
            getFriendList().then(res => {
                if (res.code === 200) {
                    let data = res.data
                    data.forEach(item => {
                        item.active = false
                        if (ctx.state.currentFriendId && ctx.state.currentFriendId === item.userId) {
                            item.active = true
                        }
                    })
                    ctx.commit('setFriendList', data)
                    resolve(res)
                } else {
                    reject(res)
                }
            }).catch(err => {
                reject(err)
                console.log(err)
            })
        })
    },

    // 将好友发送的消息设为已读
    updateFriendMsgState(ctx, data) {
        return new Promise((resolve, reject) => {
            updateFriendMsgState(data).then(res => {
                if (res.code === 200) {
                    resolve(res)
                } else {
                    reject(res)
                }
            }).catch(err => {
                reject(err)
            })
        })
    },
}

const getters = {

}

// 遍历菜单
function mapMenus(menus) {
    let data = []

    menus.forEach((item, index) => {
        if (!item.meta || !item.meta.hidden) {
            data.push({
                name: item.children[0].name,
                icon: item.children[0].meta.icon,
                path: item.children[0].path,
                meta: {
                    title: item.children[0].meta.title
                }
            })
        }
    })

    return data
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}